<template>
    <div id="box">
        <!--搜索区域-->
        <div class="search">
            <el-form :inline="true" :model="searchForm" class="demo-form-inline">
                <el-form-item label="用户名">
                    <el-input v-model="searchForm.query.username" placeholder="请输入用户名"></el-input>
                </el-form-item>
                <el-form-item label="部门">
                    <el-select v-model="searchForm.query.deptId" placeholder="请选择部门">
                        <el-option :key="dept.id" v-for="dept in deptSelect" :label="dept.deptName"
                                   :value="dept.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="状态">
                    <el-select v-model="searchForm.query.state" placeholder="请选择用户状态">
                        <el-option label="正常" :value="1"></el-option>
                        <el-option label="禁用" :value="0"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" @click="search">搜索</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-refresh" @click="clearSearch">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <!--头部按钮-->
        <div id="addBtn">
            <el-button type="primary" plain size="mini" @click="dialogFormVisible=true">新增</el-button>
            <el-button type="danger" plain size="mini" @click="batchDelete">批量删除</el-button>
        </div>
        <!--表格主体区域-->
        <el-table
                @selection-change="handleSelectionChange"
                :data="tableData"
                stripe
                height="310"
                style="width: 100%">
            <el-table-column
                    type="selection"
                    fixed
                    width="55">
            </el-table-column>
            <el-table-column prop="username" label="用户名"></el-table-column>
            <el-table-column prop="nickName" label="昵称"></el-table-column>
            <el-table-column
                    prop="sex"
                    label="性别">
                <template slot-scope="scope">
                    <span v-if="scope.row.sex==1">男</span>
                    <span v-if="scope.row.sex==0">女</span>
                </template>
            </el-table-column>
            <el-table-column prop="city" label="城市"></el-table-column>
            <el-table-column prop="tel" label="联系方式" width="150"></el-table-column>

            <el-table-column
                    prop="deptName"
                    label="部门">
            </el-table-column>

            <el-table-column
                    prop="roles"
                    label="角色" width="120">
                <template slot-scope="scope">
                    <span v-text="scope.row.roles.join(' ,')"></span>
                </template>
            </el-table-column>
            <el-table-column
                    prop="state"
                    label="状态">
                <template slot-scope="scope">
                    <el-switch
                            v-model="scope.row.state"
                            @change="stateChange(scope.row)"
                            :active-value="1"
                            :inactive-value="0"
                            active-color="#13ce66"
                            inactive-color="#ff4949">
                    </el-switch>
                </template>
            </el-table-column>

            <el-table-column
                    prop="createTime"
                    label="创建时间" width="160">
            </el-table-column>

            <el-table-column label="操作" width="225px" fixed="right">
                <template slot-scope="scope">
                    <el-button
                            size="mini"
                            @click="handleEdit(scope.$index, scope.row)">编辑
                    </el-button>

                    <el-popconfirm
                            title="确定删除吗？"
                            @confirm="handleDelete(scope.$index, scope.row)">
                        <el-button
                                style="margin-left: 5px;margin-right: 5px;"
                                slot="reference"
                                size="mini"
                                type="danger">删除
                        </el-button>
                    </el-popconfirm>

                    <el-popconfirm
                            title="确定重置密码？"
                            @confirm="resetPassword(scope.$index, scope.row)">
                        <el-button
                                slot="reference"
                                size="mini"
                                type="warning">重置密码
                        </el-button>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <!--分页器-->
        <div id="page">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="[5, 15, 30, 40]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </div>
        <!--弹出层-->
        <div>
            <el-dialog :title="title" :visible.sync="dialogFormVisible" width="35%" @close="clearDialog">
                <el-form :model="form" ref="formRef" :rules="rules" label-width="90px" size="medium"
                         label-position="right">
                    <el-input v-model="form.id" autocomplete="off" v-show="false"></el-input>
                    <el-form-item label="用户名" prop="username" v-if="title=='添加用户'">
                        <el-input v-model="form.username" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="昵称" prop="nickName">
                        <el-input v-model="form.nickName" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="性别" prop="sex">
                        <el-select v-model="form.sex" placeholder="请选择性别" style="width: 100%">
                            <el-option label="男" :value="1"></el-option>
                            <el-option label="女" :value="0"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="地址" prop="city">
                        <el-input v-model="form.city" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="联系方式" prop="tel">
                        <el-input v-model="form.tel" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="部门" prop="deptId">
                        <el-select v-model="form.deptId" placeholder="请选择部门" style="width: 100%">
                            <el-option v-for="(dept,index) in deptSelect" :label="dept.deptName" :key="index"
                                       :value="dept.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="角色" prop="roleIds" multiple>
                        <el-select v-model="form.roleIds" multiple placeholder="请选择角色" style="width: 100%">
                            <el-option v-for="(role,index) in roleList" :key="index" :label="role.roleCh"
                                       :value="role.roleId"></el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisible=false">取 消</el-button>
                    <el-button type="primary" v-if="title=='添加用户'" @click="addUser">确 定</el-button>
                    <el-button type="primary" v-if="title=='编辑用户'" @click="updateUser">确 定</el-button>
                </div>
            </el-dialog>
        </div>
    </div>

</template>
<!--
        table表格数据渲染 需要满足的规则
        1.table标签中  绑定表格数据  :data="tableData"
        2. el-table-column  中
                 prop="date"  后期需要和后台接口中返回数据的属性名保持一致  [{date:'',name:''},{}]
                 label="日期"  表格在前端页面中显示的字段名
-->
<script>
    import {
        addOrUpdate,
        addUser,
        batchDelete, editUser,
        editUserState,
        getById,
        getUserById,
        resetPassword,
        userList
    } from "@/api/user";
    import {deptSelect} from "@/api/dept";
    import {roleSelect} from "@/api/role";

    export default {
        name: 'UserView',
        data() {
            return {
                title: '添加用户',
                roleList: [],
                deptSelect: [],
                //选中复选框的值
                multipleSelection: '',
                pageSize: 5,
                currentPage: 1,
                total: 40,
                title: "添加用户",
                dialogFormVisible: false,  // 控制弹出层显示 还是隐藏
                form: {},
                rules: {
                    username: [{required: true, message: '请输入用户名', trigger: 'blur'}],
                    nickName: [{required: true, message: '请输入昵称', trigger: 'blur'}],
                    sex: [{required: true, message: '请选择性别', trigger: 'blur'}],
                    roleIds: [{required: true, message: '请选择角色', trigger: 'blur'}],
                    deptId: [{required: true, message: '请选择部门', trigger: 'blur'}],
                    tel: [{min: 11, message: '请输入正确的手机号', trigger: 'blur'}]
                },
                searchForm: {
                    page: 1,
                    limit: 5,
                    query: {
                        username: '',
                        deptId: '',
                        state: ''
                    }
                },
                tableData: []
            }
        },
        methods: {
            search() {
                this.searchForm.page = 1
                this.getUserList(this.searchForm)
            },
            updateUser() {
                this.$refs.formRef.validate(v => {
                    if (v) {
                        editUser(this.form).then(res => {
                            if (res.code == 0) {
                                this.$message({
                                    type: "success",
                                    message: res.message,
                                    onClose: () => {
                                        this.dialogFormVisible = false
                                        this.getUserList(this.searchForm);
                                    }
                                })
                            }
                        })
                    }
                })
            },
            addUser() {
                //添加用户信息  ok
                this.$refs.formRef.validate(v => {
                    if (v) {
                        addUser(this.form).then(res => {
                            if (res.code == 0) {
                                this.$message({
                                    type: "success",
                                    message: res.message,
                                    onClose: () => {
                                        this.dialogFormVisible = false
                                        this.getUserList(this.searchForm);
                                    }
                                })
                            }
                        })
                    } else {
                        this.$message.warning("请填写完整的用户信息")
                    }
                })

            },
            // 编辑用户
            handleEdit(index, row) {
                this.title = '编辑用户'
                this.dialogFormVisible = true

                //    根据用户id  查询用户信息 回显数据
                let uid = row.id
                getUserById(uid).then(res => {
                    this.form = res.data
                })

            },
            handleDelete(index, row) {
                let uid = [row.id]
                batchDelete(uid).then(res => {
                    if (res.code==0){
                        this.$message.success(res.message);
                        this.getUserList(this.searchForm)
                    }
                })
            },
            handleSizeChange(val) {
                // 发送异步请求
                console.log(`每页 ${val} 条`);
                this.pageSize = val;
                this.searchForm.limit = val;
                this.searchForm.page = this.currentPage;
                this.getUserList(this.searchForm);
            },
            handleCurrentChange(val) {
                // 发送异步请求
                console.log(`当前页: ${val}`);
                this.currentPage = val;
                this.searchForm.page = val;
                this.searchForm.limit = this.pageSize;
                this.getUserList(this.searchForm)
            },
            // 重置密码
            resetPassword(index, row) {
                let id = row.id
                resetPassword(id).then(res => {
                    if (res.code==0){
                        this.$message.success(res.message)
                    }
                })
            },
            // 批量删除  this.multipleSelection   uids
            batchDelete() {
                if (this.multipleSelection.length == 0) {
                    this.$message.warning("请至少选择一条数据!!!")
                    return;
                }

                batchDelete(this.multipleSelection).then(res => {
                    if (res.code==0){
                        this.$message.success(res.message)
                        // 重新加载数据
                        this.getUserList(this.searchForm);
                    }

                })
            },
            // 复选框 改变时回调
            handleSelectionChange(val) {
                let uids = val.map(v => v.id);
                this.multipleSelection = uids;
            },
            //改变用户状态
            stateChange(row) {
                let id = row.id
                let state = row.state
                editUserState({id, state}).then(res => {
                    if (res.code==0){
                        this.$message.success(res.message);
                        this.getUserList(this.searchForm);
                    }
                })
            },
            //清空搜索
            clearSearch() {
                this.searchForm = {
                    page: 1,
                    limit: 5,
                    query: {
                        username: '',
                        deptId: '',
                        state: ''
                    }
                }
                this.getUserList(this.searchForm)
            },
            // 清空弹出层
            clearDialog() {
                this.title = "添加用户"
                this.form = {}
                this.$refs.formRef.clearValidate()   // 清空校验信息
            },
            //用户列表
            getUserList(searchParams) {
                userList(searchParams).then(res => {
                    if (res.code==0){
                        let {pageData, total} = res.data;
                        this.tableData = pageData
                        this.total = total
                    }

                });
            }
        },
        created() {
            this.getUserList(this.searchForm)
            deptSelect().then(res => {
                if (res.code==0){
                    this.deptSelect = res.data
                }

            })
            roleSelect().then(res => {
                if (res.code==0){
                    this.roleList = res.data
                }
            })
        }
    }
</script>

<style scoped>

    #box {
        width: 95%;
        margin: 5px auto 0;
    }

    .search {
        margin-top: 40px;
        padding: 5px;
        border-bottom: 1px solid #eee;
    }

    #page {
        margin-top: 10px;
    }

    #addBtn {
        margin-top: 20px;
        margin-bottom: 20px;
    }
</style>
